<template>
  <div class="inventory-flow">
    <el-card>
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>库存流水</h2>
        <el-button type="primary" @click="refreshData">刷新数据</el-button>
      </div>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="流水单号">
          <el-input v-model="searchForm.flowId" placeholder="请输入流水单号" clearable />
        </el-form-item>
        <el-form-item label="货品名称">
          <el-input v-model="searchForm.goodsName" placeholder="请输入货品名称" clearable />
        </el-form-item>
        <el-form-item label="货品类型">
          <el-select v-model="searchForm.goodsType" placeholder="请选择货品类型" clearable>
            <el-option v-for="item in productTypes" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="流水类型">
          <el-select v-model="searchForm.flowType" placeholder="请选择流水类型" clearable>
            <el-option label="入库" value="IN" />
            <el-option label="出库" value="OUT" />
            <el-option label="调拨" value="TRANSFER" />
            <el-option label="盘点" value="CHECK" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库">
          <el-select v-model="searchForm.warehouseId" placeholder="请选择仓库" clearable>
            <el-option v-for="item in warehouses" :key="item.warehouseId" :label="item.warehousename" :value="item.warehouseId" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchFlowList">查询</el-button>
          <el-button @click="resetSearchForm">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 统计卡片 -->
      <div class="statistics-cards">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ flowStats.totalCount }}</div>
                <div class="stat-label">总流水数</div>
              </div>
              <el-icon class="stat-icon"><Document /></el-icon>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ flowStats.inCount }}</div>
                <div class="stat-label">入库流水</div>
              </div>
              <el-icon class="stat-icon"><ArrowDown /></el-icon>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ flowStats.outCount }}</div>
                <div class="stat-label">出库流水</div>
              </div>
              <el-icon class="stat-icon"><ArrowUp /></el-icon>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ flowStats.transferCount }}</div>
                <div class="stat-label">调拨流水</div>
              </div>
              <el-icon class="stat-icon"><Switch /></el-icon>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 数据表格 -->
      <el-table :data="flowList" border style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="flowId" label="流水单号" width="180" />
        <el-table-column prop="flowType" label="流水类型" width="100">
          <template #default="scope">
            <el-tag :type="getFlowTypeTag(scope.row.flowType)">
              {{ getFlowTypeText(scope.row.flowType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="goodsCode" label="货品编号" width="120" />
        <el-table-column prop="goodsName" label="货品名称" width="150" />
        <el-table-column prop="goodsType" label="货品类型" width="120" />
        <el-table-column prop="warehouseName" label="仓库名称" width="120" />
        <el-table-column prop="locationName" label="库位名称" width="120" />
        <el-table-column prop="quantity" label="数量" width="100" />
        <el-table-column prop="unitPrice" label="单价" width="100" />
        <el-table-column prop="totalAmount" label="总金额" width="120" />
        <el-table-column prop="operator" label="操作人" width="100" />
        <el-table-column prop="flowTime" label="流水时间" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.flowTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="150" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button type="info" size="small" @click="viewDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="流水详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="流水单号">{{ detailData.flowId }}</el-descriptions-item>
        <el-descriptions-item label="流水类型">
          <el-tag :type="getFlowTypeTag(detailData.flowType)">
            {{ getFlowTypeText(detailData.flowType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="货品编号">{{ detailData.goodsCode }}</el-descriptions-item>
        <el-descriptions-item label="货品名称">{{ detailData.goodsName }}</el-descriptions-item>
        <el-descriptions-item label="货品类型">{{ detailData.goodsType }}</el-descriptions-item>
        <el-descriptions-item label="规格型号">{{ detailData.spec }}</el-descriptions-item>
        <el-descriptions-item label="仓库名称">{{ detailData.warehouseName }}</el-descriptions-item>
        <el-descriptions-item label="库位名称">{{ detailData.locationName }}</el-descriptions-item>
        <el-descriptions-item label="数量">{{ detailData.quantity }}</el-descriptions-item>
        <el-descriptions-item label="单位">{{ detailData.unit }}</el-descriptions-item>
        <el-descriptions-item label="单价">{{ detailData.unitPrice }}</el-descriptions-item>
        <el-descriptions-item label="总金额">{{ detailData.totalAmount }}</el-descriptions-item>
        <el-descriptions-item label="操作人">{{ detailData.operator }}</el-descriptions-item>
        <el-descriptions-item label="流水时间">{{ formatDate(detailData.flowTime) }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailData.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, ArrowDown, ArrowUp, Switch } from '@element-plus/icons-vue'
import axios from 'axios'

// 响应式数据
const loading = ref(false)
const detailDialogVisible = ref(false)

// 搜索表单
const searchForm = reactive({
  flowId: '',
  goodsName: '',
  goodsType: '', // 新增
  flowType: '',
  warehouseId: '',
  dateRange: []
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 统计数据
const flowStats = reactive({
  totalCount: 0,
  inCount: 0,
  outCount: 0,
  transferCount: 0
})

// 表格数据
const flowList = ref<any[]>([])
const warehouses = ref<{ warehouseId: string; warehousename: string }[]>([])
const productTypes = ref<any[]>([])
const units = ref<any[]>([])

// 详情数据
const detailData = reactive({
  flowId: '',
  flowType: '',
  goodsCode: '',
  goodsName: '',
  goodsType: '',
  spec: '',
  warehouseName: '',
  locationName: '',
  quantity: 0,
  unit: '',
  unitPrice: 0,
  totalAmount: 0,
  operator: '',
  flowTime: '',
  remark: ''
})

// 生成假数据
const generateMockData = () => {
  const mockFlowList = []
  const flowTypes = ['IN', 'OUT', 'TRANSFER', 'CHECK']
  const goodsList = [
    { code: 'SP202508011001', name: '联想Y7000P', type: '电脑', spec: '20*10', unit: '台', price: 5999 },
    { code: 'SP202508011002', name: '可口可乐', type: '饮料', spec: '200ml', unit: '瓶', price: 3.5 },
    { code: 'SP202508011003', name: '三锅头', type: '酒类', spec: '500ml', unit: '瓶', price: 25 },
    { code: 'SP202508011004', name: '华为Mate60', type: '手机', spec: '6.7寸', unit: '台', price: 6999 },
    { code: 'SP202508011005', name: '苹果iPhone15', type: '手机', spec: '6.1寸', unit: '台', price: 7999 }
  ]
  const warehouses = [
    { id: 'WH001', name: '零件仓库' },
    { id: 'WH002', name: '颜料仓库' },
    { id: 'WH003', name: '后勤仓库' },
    { id: 'WH004', name: '机械仓库' },
    { id: 'WH005', name: '食品仓库' }
  ]
  const locations = ['库位一', '库位二', '库位三', '库位四', '库位五']
  const operators = ['张三', '李四', '王五', '赵六', '钱七']
  const remarks = [
    '正常入库',
    '客户订单出库',
    '仓库调拨',
    '月度盘点',
    '紧急补货',
    '质量检验',
    '库存调整',
    '季节性备货'
  ]

  // 生成50条假数据
  for (let i = 1; i <= 50; i++) {
    const goods = goodsList[Math.floor(Math.random() * goodsList.length)]
    const warehouse = warehouses[Math.floor(Math.random() * warehouses.length)]
    const flowType = flowTypes[Math.floor(Math.random() * flowTypes.length)]
    const quantity = Math.floor(Math.random() * 100) + 1
    const unitPrice = goods.price
    const totalAmount = quantity * unitPrice
    
    mockFlowList.push({
      flowId: `FL${String(i).padStart(6, '0')}`,
      flowType: flowType,
      goodsCode: goods.code,
      goodsName: goods.name,
      goodsType: goods.type,
      spec: goods.spec,
      warehouseName: warehouse.name,
      locationName: locations[Math.floor(Math.random() * locations.length)],
      quantity: quantity,
      unit: goods.unit,
      unitPrice: unitPrice,
      totalAmount: totalAmount,
      operator: operators[Math.floor(Math.random() * operators.length)],
      flowTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
      remark: remarks[Math.floor(Math.random() * remarks.length)]
    })
  }

  return mockFlowList
}

// 获取流水列表
const fetchFlowList = async () => {
  loading.value = true
  try {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 生成假数据
    const allMockData = generateMockData()
    
    // 根据搜索条件过滤数据
    let filteredData = allMockData.filter(item => {
      if (searchForm.flowId && !item.flowId.includes(searchForm.flowId)) return false
      if (searchForm.goodsName && !item.goodsName.includes(searchForm.goodsName)) return false
      if (searchForm.flowType && item.flowType !== searchForm.flowType) return false
      if (searchForm.warehouseId && item.warehouseName !== searchForm.warehouseId) return false
      return true
    })
    
    // 分页处理
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    flowList.value = filteredData.slice(start, end)
    pagination.total = filteredData.length
    
    // 计算统计数据
    const stats = {
      totalCount: filteredData.length,
      inCount: filteredData.filter(item => item.flowType === 'IN').length,
      outCount: filteredData.filter(item => item.flowType === 'OUT').length,
      transferCount: filteredData.filter(item => item.flowType === 'TRANSFER').length
    }
    Object.assign(flowStats, stats)
    
  } catch (error) {
    ElMessage.error('获取流水列表失败')
    console.error('获取流水列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取仓库列表
const fetchWarehouses = async () => {
  try {
    // 使用假数据
    warehouses.value = [
      { warehouseId: 'WH001', warehousename: '零件仓库' },
      { warehouseId: 'WH002', warehousename: '颜料仓库' },
      { warehouseId: 'WH003', warehousename: '后勤仓库' },
      { warehouseId: 'WH004', warehousename: '机械仓库' },
      { warehouseId: 'WH005', warehousename: '食品仓库' }
    ]
  } catch (error) {
    console.error('获取仓库列表失败:', error)
  }
}

// 获取货品类型列表
const fetchProductTypes = async () => {
  try {
    // 使用假数据
    productTypes.value = ['电脑', '饮料', '酒类', '手机', '服装', '食品', '日用品']
  } catch (error) {}
}

// 获取单位列表
const fetchUnits = async () => {
  try {
    // 使用假数据
    units.value = ['台', '瓶', '件', '个', '箱', '包', '盒']
  } catch (error) {}
}

// 重置搜索表单
const resetSearchForm = () => {
  Object.assign(searchForm, {
    flowId: '',
    goodsName: '',
    flowType: '',
    warehouseId: '',
    dateRange: []
  })
  pagination.currentPage = 1
  fetchFlowList()
}

// 刷新数据
const refreshData = () => {
  fetchFlowList()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchFlowList()
}

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchFlowList()
}

// 获取流水类型标签样式
const getFlowTypeTag = (type: string) => {
  const typeMap: Record<string, string> = {
    'IN': 'success',
    'OUT': 'danger',
    'TRANSFER': 'warning',
    'CHECK': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取流水类型文本
const getFlowTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    'IN': '入库',
    'OUT': '出库',
    'TRANSFER': '调拨',
    'CHECK': '盘点'
  }
  return typeMap[type] || type
}

// 查看详情
const viewDetail = (row: any) => {
  Object.assign(detailData, row)
  detailDialogVisible.value = true
}

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return '-'
  return new Date(date).toLocaleString()
}

// 页面加载时初始化
onMounted(() => {
  fetchWarehouses()
  fetchFlowList()
  fetchProductTypes()
  fetchUnits()
})
</script>

<style scoped>
.inventory-flow {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  position: relative;
  overflow: hidden;
}

.stat-content {
  text-align: center;
  padding: 20px 0;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.stat-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 48px;
  color: #E1F3FF;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
}
</style> 